#include "QQMaskWidget.h"

QQMaskWidget::QQMaskWidget(QWidget* parent, QQMaskWidget::MaskType type)
	: QWidget(parent)
{
	this->setObjectName("QQMaskWidget");
	this->setStyleSheet("#QQMaskWidget{background-color:transparent;}");
	mType = type;
	mMaskAlpha = 0;
	mMaskRadius = 50;
	mBlurEffect = new QGraphicsBlurEffect(this);
	mBlurEffect->setBlurRadius(mMaskRadius);
}

QQMaskWidget::~QQMaskWidget()
{
}

void QQMaskWidget::setMaskAlpha(int MaskAlpha)
{
	mMaskAlpha = MaskAlpha;
	update();
	emit maskAlphaChanged();
}

int QQMaskWidget::getMaskAlpha() const
{
	return mMaskAlpha;
}

void QQMaskWidget::setMaskRadius(int MaskRadius)
{
	mMaskRadius = MaskRadius;
	mBlurEffect->setBlurRadius(mMaskRadius);
	emit maskRadiusChanged();
}

int QQMaskWidget::getMaskRadius() const
{
	return mMaskRadius;
}

void QQMaskWidget::setMaskType(QQMaskWidget::MaskType type)
{
	mType = type;
}

QQMaskWidget::MaskType QQMaskWidget::getMaskType() const
{
	return mType;
}

void QQMaskWidget::doMaskAnimation(int endValue)
{
	QPropertyAnimation* opacityAnimation = new QPropertyAnimation(this, "mMaskAlpha");
	connect(opacityAnimation, &QPropertyAnimation::valueChanged, this, [=](const QVariant& value) {
		update();
		});
	connect(opacityAnimation, &QPropertyAnimation::finished, this, [=]() {
		if (endValue == 0)
		{
			setVisible(false);
		}
		});
	opacityAnimation->setEasingCurve(QEasingCurve::InOutSine);
	opacityAnimation->setDuration(250);
	opacityAnimation->setStartValue(mMaskAlpha);
	opacityAnimation->setEndValue(endValue);
	opacityAnimation->start(QAbstractAnimation::DeleteWhenStopped);
}

void QQMaskWidget::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.save();
	painter.setPen(Qt::NoPen);
	painter.setRenderHint(QPainter::Antialiasing);
	switch (mType)
	{
	case QQMaskWidget::MaskType::Normal:
	{
		painter.setBrush(QColor(0x00, 0x00, 0x00, mMaskAlpha));
		painter.drawRect(rect());
		break;
	}
	case QQMaskWidget::MaskType::Vague:
	{
		QPixmap pixmap(size());
		parentWidget()->render(&pixmap);
		QGraphicsScene scene;
		QGraphicsPixmapItem item;
		item.setPixmap(pixmap);
		QGraphicsBlurEffect effect;
		effect.setBlurRadius(mMaskRadius);
		item.setGraphicsEffect(&effect);
		scene.addItem(&item);
		QPixmap result(pixmap.size());
		result.fill(Qt::transparent);
		QPainter result_painter(&result);
		scene.render(&result_painter, QRectF(), QRectF(0, 0, pixmap.width(), pixmap.height()));
		painter.drawPixmap(rect(), pixmap);
		break;
	}
	default:
		break;
	}

	painter.restore();

	return QWidget::paintEvent(event);
}
